from uuid import uuid4
import os

from rest_framework import serializers

from .models import Scripts
from util.exception import ValidationError
from django.conf import settings


class ScriptsSeriallizer(serializers.ModelSerializer):
    name = serializers.CharField(max_length=100, allow_null=False, allow_blank=False)

    class Meta:
        model = Scripts
        fields = ["name"]

    def validate_name(self, obj):
        sc = Scripts.objects.filter(name=obj, is_delete=False).first()
        if sc:
            raise ValidationError(50001)
        else:
            return obj

    def create(self, data):
        id = str(uuid4()).replace("-", "")
        data["id"] = id
        data["file_path"] = "".join([settings.SCRIPTS_FILE_DIR, "/", data["name"]])
        self.__create_dir(data["file_path"])
        Scripts.objects.create(**data)

    def __create_dir(self, filepath):
        if not os.path.isdir(filepath):
            os.mkdir(filepath)


class ScriptsListSeriallizer(serializers.ModelSerializer):
    class Meta:
        model = Scripts
        fields = ["name", "id"]


class ScriptsUpdateSeriallizer(serializers.ModelSerializer):
    id = serializers.CharField(max_length=32, allow_blank=False, allow_null=False)

    class Meta:
        model = Scripts
        fields = ["id"]

    def update(self, instance, validated_data):
        if instance:
            instance.is_delete = True
            instance.save()
            file_path = "".join([settings.SCRIPTS_FILE_DIR, "/", instance.name])
            if os.path.isdir(file_path):
                os.rmdir(file_path)


class ScriptsFileDeleteSeriallizer(serializers.ModelSerializer):
    id = serializers.CharField(max_length=32, allow_blank=False, allow_null=False)
    files = serializers.ListField(allow_null=False)

    class Meta:
        model = Scripts
        fields = ["id", "files"]


class ScriptsFileShowSeriallizer(serializers.ModelSerializer):
    id = serializers.CharField(max_length=32, allow_blank=False, allow_null=False)
    file_name = serializers.CharField(allow_null=False)

    class Meta:
        model = Scripts
        fields = ["id", "file_name"]

class ScriptsFileContentSeriallizer(serializers.ModelSerializer):
    id = serializers.CharField(max_length=32, allow_blank=False, allow_null=False)
    file_name = serializers.CharField(allow_null=False)
    content = serializers.CharField(allow_null=False)

    class Meta:
        model = Scripts
        fields = ["id", "file_name", "content"]
